
import Pagination from '@/components/pagination';
import mixin from '@/service/mixin';
import alertDialog from '@/components/alert-dialog';
import keyMap from '@/config/key-map';
import SelectAppList from '@/components/select-app-list';
import {regExp} from '@/config/index';

let that = null;
export default {
    name: 'telemarketing-userManage',
    components: {
        Pagination,
        alertDialog,
        SelectAppList,
    },
    mixins: [mixin],
    data() {
        let templateChange = ((rule, value, callback) => {
            if(this.showRobotScriptTemplate&&value==''){
                callback(new Error(this.$t('verify.plsChoose')));
            }else{
                callback()
            }
        })
        return {
            robotTemplate:[],
            showRobotScriptTemplate:false,
            keyMap,
            language: this.$storage.getLocal('language'),
            formLabelWidth: '100px',
            alertDialogVisible: {
                importUser: false, // 用户导入
                editingStatement: false, // 编辑话述
                wordTemplateSelect: false, // 话术模板选择
                assignmentUser: false // 用户分配
            },
            alertDialogMsg: {},
            form: {
                batchCode: '',
                currentStatus: null,
                importDate: [],
                // importDateStart: "",
                // importDateEnd: "",
                marketingType: '',
                appName: '',
            },
            importUserForm: {
                file: '',
                batchCode: '',
                remark: '',
                // importCode: '',
                isSyncSale: 1,
                couponUrl: '',
                appName: [],
                templateId:'',
                marketingType: '2',
            },
            importUserFormRules: {
                file:[{ required: true, message: this.$t('verify.onlyExcelFile'), trigger: 'blur' }],
                // importCode:[{ required: true, message: this.$t('authority.inputEverydayCase'), trigger: 'blur' }],
                // remark:'',
                batchCode: [
                    { required: true, message: this.$t('verify.plsInput'), trigger: 'blur' },
                    { pattern: /^[a-zA-Z]{2}\d{6}$/, message: this.$t('salesManage.batchNumberRule'), trigger: 'blur' }
                ],
                isSyncSale: [
                    { required: true, message: this.$t('verify.plsChoose'), trigger: 'blur' },
                ],
                appName: [
                    { required: true, message: this.$t('verify.plsChoose'), trigger: 'blur' },
                ],
                couponUrl: [
                    { pattern: regExp.url, message: this.$t('verify.plsEnterRightUrl'), trigger: 'blur' },
                ],
                templateId: [
                    { validator: templateChange, trigger: 'blur' },
                ],
            },
            telSalesList: [],
            assignmentUserForm: {
                checkList: [],
            },
            statusList: [
                { value: '', label: this.$t('common.all') }, // 全部
                { value: 0, label: this.$t('pageTitle.waitAssign') },
                { value: 1, label: this.$t('salesManage.assigned') },
                { value: 2, label: this.$t('salesManage.recycled') }
            ], // 状态
            editingStatementObj: {
                batchCode: '',
                batchId: '',
                list: [
                    // {
                    //   questionType: 1,
                    //   isMust:1,
                    //   content: "",
                    //   list: [{ content: "" },{ content: "" }]
                    // },
                    // {
                    //   questionType: 2,
                    //   isMust:2,
                    //   content: "",
                    //   list: [{ content: "453" }]
                    // },

                    // {
                    //   questionType: 3,
                    //   isMust:2,
                    //   content: "",
                    //   list: [{ content: "453" }]
                    // }
                ]
            },
            tableData: [],
            fileList: [],  // 导入用户excel
            fileNameList: '',
            ruleForm: [],
            rules: {},
            wordTemplateSelectF: {
                questionnaireId: '',
                batchId: '',
                batchCode: ''
            },
            wordTemplateRule: {
                questionnaireId: [
                    { required: true, message: this.$t('verify.plsChoose'), trigger: 'blur' },
                ],
            },
            templateList: [],
            distributionUser: {
                batchCode: '',
                importId: '',
                numDtoList: [
                    // { salesmanId: '', num: '' }
                ],
                userNum: 0
            },
        };
    },
    methods: {
        wordTemplateSelect(row) {
            this.$refs.wordTemplateSelectF.resetFields();
            // this.wordTemplateSelectF = {
            //   questionnaireId: '',
            //   batchId: '',
            //   batchCode: ''
            // };
            this.wordTemplateSelectF.batchId = row.batchId;
            this.wordTemplateSelectF.batchCode = row.batchCode;
            this.wordTemplateSelectF.questionnaireId = row.templateId || '';

            this.$api.telSales.listTemplate({ name: '' }).then((res) => {
                const { status, data, error, msg } = res;
                if (status === '1' && error === '00000000') {
                    this.templateList = data;
                    // this.$message({
                    //   type: 'success',
                    //   message: this.$t('authority.verifySucc') + '!'
                    // });
                    // 话述模板选择
                    this.alertDialogVisible.wordTemplateSelect = true;
                } else {
                    this.$message({
                        type: 'error',
                        message: msg
                    });
                }
            });
        },
        addFile() {
            const inputDOM = this.$refs.excelImportUser;
            // 通过DOM取文件数据
            const flag = this.beforeAvatarUpload(inputDOM.files[0]);
            if (flag) {
                this.importUserForm.file = inputDOM.files[0];
                this.fileNameList = this.importUserForm.file.name;
            }
        },
        // 文件上传前
        beforeAvatarUpload(file) {
            let flag = false;
            const arr = file.name.split('.');
            const ext = arr[arr.length - 1];
            if (ext && (ext === 'xls' || ext === 'xlsx' || ext === 'csv')) {
                flag = true;
            } else {
                this.$message.warning(this.$t('verify.onlyExcelFile')); // '只能上传Excel文件！'
            }
            return flag;
        },
        // 批量上传成功
        handleUploadSuccess(res, file) {
            const { status, data, msg } = res;
            this.uploadLoading = false;
            if (status === '1') {
                this.$message.success(msg || 'upload success!');
                this.getTableData();
                this.showUploadDialog = false;
            } else {
                this.$message.error(msg || 'upload error, please try again!'); // 文件上传出错，请稍后重试！
            }
        },
        submtWordTemplate() {
            this.$refs.wordTemplateSelectF.validate((valid) => {
                if (valid) {
                    this.$confirm(`<p>${this.$t('salesManage.batchNumber')}: <span>${this.wordTemplateSelectF.batchCode}</span></p><p>${this.$t('salesManage.choiceWord')}: ${this.questionnaireName} </p><p>${this.$t('salesManage.tipsWordTemplate')} </p> `, this.$t('salesManage.confirmWordTemplate'), {
                        confirmButtonText: this.$t('common.confirm'),
                        cancelButtonText: this.$t('common.cancel'),
                        dangerouslyUseHTMLString: true
                    }).then(() => {
                        this.confirmWordTemplate(this.editingStatementObj);
                    }).catch(() => {
                    });
                } else {
                    return false;
                }
                return true;
            });
        },
        confirmWordTemplate() {
            // this.wordTemplateSelectF.
            const params = {
                batchId: this.wordTemplateSelectF.batchId,
                questionnaireId: this.wordTemplateSelectF.questionnaireId,
            };
            this.$api.telSales.setQuestionnaire(params).then((res) => {
                const { status, error, msg } = res;
                if (status === '1' && error === '00000000') {
                    this.$message.success(this.$t('common.successfulOperation'));
                    this.alertDialogVisible.wordTemplateSelect = false;
                    this.getTableData();
                } else {
                    this.$message({
                        type: 'error',
                        message: msg
                    });
                }
            });
        },
        addEditState(type) {
            switch (type) {
                case 1:
                    this.editingStatementObj.list.push({
                        questionType: 1,
                        isMust: 1,
                        content: '',
                        list: [{ content: '' }]
                    });
                    break;
                case 2:
                    this.editingStatementObj.list.push({
                        questionType: 2,
                        isMust: 1,
                        content: '',
                        list: [{ content: '' }]
                    });
                    break;
                case 3:
                    this.editingStatementObj.list.push({
                        questionType: 3,
                        isMust: 1,
                        content: '',
                        list: [{ content: '' }]
                    });
                    break;
                default:
                    break;
            }
            const ele = this.$refs.editingStatementWrap;
            this.$nextTick(() => {
                ele.scrollTop = ele.scrollHeight;
            });
        },
        addOptionState(indexBlock) {
            this.editingStatementObj.list[indexBlock].list.push({ content: '' });
        },
        deleteOptionState(indexBlock) {
            this.editingStatementObj.list[indexBlock].list.pop({ content: '' });
        },
        deleteOptionBlock(indexBlock) {
            this.editingStatementObj.list.splice(indexBlock, 1);
        },
        // 分配电销员
        distribution(row) {
            this.assignmentUserForm.checkList = [];
            this.$refs.assignmentUserForm.resetFields();
            this.distributionUser = {
                batchCode: row.batchCode,
                importId: row.id,
                numDtoList: [],
                userNum: row.userNum
            };
            const params = {
                appName: row.appName,
                marketingType: row.marketingType,
            };
            this.$api.telSales.listCanDistribution(params).then((res) => {
                const { status, data, error } = res;
                if (status === '1' && error === '00000000') {
                    this.alertDialogVisible.assignmentUser = true;

                    data.forEach((item) => { item.numInput = ''; });
                    // this.$set(this,'telSalesList',data);
                    this.telSalesList = data;
                } else {
                    this.alertDialogVisible.assignmentUser = false;
                }
            });
        },
        // 回收
        recycling(row) {
            // this.$confirm(this.$tc('salesManage.tipsConfirmRecycling'), this.$tc('salesManage.confirmationRecycling'), {
            this.$api.telSales.getUserDetailByBatchCode({ batchCode: row.batchCode }).then(res => {
                // rate 达成率 agreeCount 达成数 totalCount 总数
                const { status, data } = res;
                if ('1' === status && data) {
                    const content = `
                    <p>${this.$t('salesManage.achievementRate')}： ${data.rate}</p>
                    <p>${this.$t('salesManage.numberReached')}： ${data.agreeCount}</p>
                    <p>${this.$t('salesManage.totalUsers')}： ${data.totalCount}</p>
                    `;
                    this.$confirm(content, this.$tc('salesManage.confirmationRecycling'), {
                        confirmButtonText: this.$t('common.confirm'),
                        cancelButtonText: this.$t('common.cancel'),
                        dangerouslyUseHTMLString: true,
                        // type: 'warning'
                    })
                        .then(() => {
                            this.recyclingConfirm(row);
                        })
                        .catch(() => {
                            // this.$message({
                            //   type: 'info',
                            //   message: '已取消回收'
                            // });
                        });
                }
            });
        },
        // 回收确认
        recyclingConfirm(row) {
            const params = {
                batchCode: row.batchCode,
                importId: row.id
            };
            this.$api.telSales.recyclingUser(params).then((res) => {
                const { status, data, error } = res;
                if (status === '1' && error === '00000000') {
                    this.$message.success(this.$tc('salesManage.successfulRecovery'));
                    // this.$alert(
                    //     `
                    //         <p>${this.$t('salesManage.timeRecovery')}:${data.recyclingDate} </p>
                    //         <p>${this.$t('salesManage.expired')}:${data.invalidNum} ${this.$t('salesManage.individual')} ,
                    //         ${this.$t('salesManage.achieved')}${data.agreeNum} ${this.$t('salesManage.individual')} </p>`,
                    //     this.$tc('salesManage.confirmationRecycling'),
                    //     {
                    //         confirmButtonText: this.$tc('common.confirm'),
                    //         dangerouslyUseHTMLString: true
                    //     }
                    // ).then(() => {});
                    this.getTableData();
                }
            });
        },
        // 导出话述
        exportStatement(row) {
            // 导出数据
            const params = {
                importId: row.id
            };
            const user = this.$storage.get('user');
            const language = this.$storage.getLocal('language');
            params.token = user.token;
            params.language = language;
            params.Authorization = 'Basic cGluamFtYW5nbzpwaW5qYW1hbmdvMDE4';
            const {$apiConf} = this;
            const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.telSales.exportTmUserBatch, ['page']);
            this.$openNewBlank(url);
        },
        search() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.getTableData({ currentPage: 1 }, this.form);
                } else {
                    this.$message.error(this.$t("verify.plsCheckFilters"));
                }
            });
        },
        submitIUser() {
            this.$refs.importUserForm.validate((valid) => {
                if (valid) {
                    if (this.importUserForm.file.length < 1) {
                        this.$message.warning(this.$tc('verify.onlyExcelFile'));
                        return false;
                    }
                    const params = new FormData();
                    Object.keys(this.importUserForm).forEach((key) => {
                        if (!(this.importUserForm[key] instanceof Array)) {
                            
                            params.append(key, this.importUserForm[key]);
                        }
                    });
                    let templateName = '';
                    this.robotTemplate.forEach(item=>{
                        if(item.workflow_template_id==this.importUserForm.templateId){
                            templateName = item.name
                        }
                    });
                    params.append('appName', this.importUserForm.appName.join(','));
                    params.append('templateName', templateName)
                    this.$api.telSales.importTmUserBatch(params).then((res) => {
                        const { status, data, error } = res;
                        if (status === '1' && error === '00000000') {
                            this.$alert(
                                `
                                    <p>${this.$t('salesManage.timeImport')}: ${this.$options.filters.formatDate(data.createTime, 'yyyy-MM-dd hh:mm:ss')}</p>
                                    <p>
                                        ${this.$t('salesManage.importedSucc')}:${data.successCount} ${this.$t('salesManage.individual')},
                                        ${this.$t('salesManage.failed')}${data.failCount} ${this.$t('salesManage.individual')} 
                                    </p>`,
                                this.$tc('salesManage.confirmImportUser'),
                                {
                                    confirmButtonText: this.$t('common.confirm'),
                                    dangerouslyUseHTMLString: true
                                }
                            ).then(() => {});
                            this.alertDialogVisible.importUser = false;
                            this.getTableData();
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        submitAssignUser() {
            this.$refs.assignmentUserForm.validate((valid) => {
                if (valid) {
                    // 分配用户
                    const params = {
                        batchCode: this.distributionUser.batchCode,
                        importId: this.distributionUser.importId,
                        numDtoList: []
                    };
                    this.telSalesList.forEach((item) => {
                        if (this.assignmentUserForm.checkList.indexOf(item.userId) > -1) {
                            params.numDtoList.push({ salesmanId: item.userId, num: item.numInput });
                        }
                    });

                    this.$api.telSales.distributionUser(params).then((res) => {
                        const { status, error } = res;
                        if (status === '1' && error === '00000000') {
                            this.$alert(
                                `<p>${this.$t('salesManage.allotSucc')}!</p>`,
                                this.$tc('salesManage.confirmAllocation'),
                                {
                                    confirmButtonText: this.$tc('common.confirm'),
                                    dangerouslyUseHTMLString: true
                                }
                            ).then(() => {});
                            this.alertDialogVisible.assignmentUser = false;
                            this.getTableData();
                        } else {
                            this.$alert(
                                `<p>${this.$t('salesManage.failAllocation')}!</p>`,
                                this.$tc('salesManage.confirmAllocation'),
                                {
                                    confirmButtonText: this.$tc('common.confirm'),
                                    dangerouslyUseHTMLString: true
                                }
                            ).then(() => {});
                        }
                    });
                }
            });
        },
   
        //
        queryAssignConfig(){
            this.$api.telSales.queryAssignConfig().then(res => {
                const { status, data, error } = res;
                if ('1' === status && '00000000' === error && data) {
                    this.alertDialogVisible.importUser = true;
                    if(data.whiteListStatus==1){
                        this.showRobotScriptTemplate = true;
                        this.getAllTemplate()
                    }
                };
            });
        },
        getAllTemplate(){
            this.$api.telSales.getAllTemplate().then(res => {
                const { status, data, error } = res;
                if ('1' === status && '00000000' === error && data) {
                   this.robotTemplate = data
                };
            });
        },
        importUser() {
            this.$api.telSales.getImportCode({}).then((res) => {
                const { status, data, error } = res;
                if (status === '1' && error === '00000000') {
                    this.importUserForm.importCode = data || '';
                }
            });
            this.queryAssignConfig()
            this.showRobotScriptTemplate = false;
            this.alertDialogVisible.importUser = true;
            // 清楚上一个的验证，以及表单数据
            this.$nextTick(() => {
                this.$refs.importUserForm.resetFields();
                this.fileNameList = '';
                this.$refs.excelImportUser.value = '';
            });
        },
        getTableData(page = this.page, opts = this.form) {
            const params = this.handleParams(page, opts);
            this.$api.telSales.getTmUserBatchList(params).then((res) => {
                const { status, data, error } = res;
                if (status === '1' && error === '00000000') {
                    this.tableData = data.resultData || [];
                    this.setPage(data.page, this.page);
                }
            });
        },
        handleParams(page = this.page, opts = this.form) {
            const params = {
                batchCode: '',
                currentStatus: '',
                // importDate:[],
                importDateStart: '',
                importDateEnd: '',
                marketingType: '',
                appName: '',
                page: {
                    pageNo: page.currentPage,
                    pageSize: this.page.pageSize
                }
            };

            if (opts) {
                Object.keys(params).forEach((key) => {
                    if (typeof opts[key] !== 'undefined') {
                        params[key] = opts[key];
                    }
                });
            }
            if (this.form.importDate && this.form.importDate.length) {
                params.importDateStart = this.form.importDate[0];
                params.importDateEnd = this.form.importDate[1];
            }
            return params;
        },
        telSalesChecked(itemCheckBoxValue) {
            return this.assignmentUserForm.checkList.indexOf(itemCheckBoxValue) === -1;
        },
        // 修改优惠券链接
        handleChangeCoupon(row) {
            console.warn(row.couponUrl)
            const me = this;
            // '优惠券'
            let promitObj = {
                confirmButtonText: this.$tc('common.confirmOk'),
                cancelButtonText: this.$tc('common.cancel'),
                inputPattern: regExp.url,
                inputErrorMessage: this.$tc('verify.plsEnterRightUrl'),
                inputPlaceholder: this.$tc('common.coupons'),
                closeOnClickModal: false,
            };
            if(row.couponUrl&&row.couponUrl!==''){
                promitObj.inputValue = row.couponUrl
            };
            this.$prompt('', this.$tc('common.coupons'), 
            {
                ...promitObj,
                beforeClose(action, instance, done) {
                    const { inputValue } = instance;
                    // console.log(action, inputValue);
                    if ('confirm' === action) {
                        const { batchCode, id } = row;
                        if (inputValue.length > 255) {
                            this.$message.warning(me.$t('verify.underXWords', { x: 255 })); // 255字以内
                            return ;
                        }
                        const params = {
                            id,
                            batchCode,
                            couponUrl: inputValue,
                        };
                        return me.$api.telSales.updateCouponUrl(params).then(res => {
                            const  { status } = res;
                            if ('1' === status) {
                                me.getTableData();
                                done();
                            }
                        });
                    } else {
                        done();
                    }
                },
            }).then(() => {
                // {value}
            }).catch(() => {});
        },
    },
    computed: {
        questionnaireName() {
            const selectObj = this.templateList.filter(item => item.id === this.wordTemplateSelectF.questionnaireId);
            return selectObj[0].name || '';
        },
        assignmentUserFormRule () {
            const validateCheckList = (rule, value, callback) => {
                if (value.length === 0) {
                    callback(new Error(this.$tc('verify.plsChoose')));
                } else {
                    let total = 0;
                    const pattern = /^[1-9]\d*$/;
                    this.telSalesList.forEach((item) => {
                        if (this.assignmentUserForm.checkList.indexOf(item.userId) > -1) {
                            if (pattern.test(item.numInput)) {
                                const inputNum = +item.numInput;
                                if (inputNum > item.num) {
                                    callback(new Error(this.$tc('salesManage.assignmentMaxNumError')));
                                } else {
                                    total += inputNum;
                                }
                            } else {
                                callback(new Error(this.$tc('salesManage.tipsErrAssignmentUser')));
                            }
                        }
                    });
                    if (total > this.distributionUser.userNum) {
                        callback(new Error(this.$tc('salesManage.tipsAssignmentUser')));
                    }
                    callback();
                }
            };
            return {
                checkList: [
                    { required: true, validator: validateCheckList, trigger: ['blur', 'change'] }
                ],
            };
        },
    },
    filters: {
        currentStatus(type) {
            // 当前状态：0 待分配  1 已分配  2 已回收
            switch (type) {
                case 0:
                    return that.$t('tel.waitAssign');
                case 1:
                    return that.$t('salesManage.assigned');
                case 2:
                    return that.$t('salesManage.recycled');
                default:
                    return '--';
            }
        }
    },
    created() {
        that = this;
        this.getTableData();
        this.tableMaxHeight = window.document.body.clientHeight - 280;
    }
};
